package com.foreknow.service.impl;

import com.alibaba.fastjson.JSON;
import com.foreknow.dao.RuleMapper;
import com.foreknow.dao.SchedulingMapper;
import com.foreknow.entity.Rule;
import com.foreknow.entity.Scheduling;
import com.foreknow.service.SchedulingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class SchedulingServiceImpl implements SchedulingService {

    @Autowired
    private SchedulingMapper schedulingMapper;
    @Autowired
    private RuleMapper ruleMapper;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return 0;
    }

    @Override
    public int deleteByConditionByLogic(String starttime,Integer deptid) {
        Scheduling scheduling = new Scheduling();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        try {
            date = df.parse(starttime);
            scheduling.setDeptid(deptid);
            scheduling.setScheddate(date);
            return schedulingMapper.deleteByConditionByLogic(scheduling);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }

    @Override
    public int insert(String starttime,String overtime,List<Rule> ruleList) {

        Map<String, Object> map = new HashMap<>();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date start = new Date();
        Date over = new Date();
        try {//字符转为日期类型
            start=df.parse(starttime);
            over=df.parse(overtime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //插入是否成功
        int flag=0;
        //遍历 ruleList
        for (Rule rule : ruleList) {
            //一个科室 规则名下的 规则集合
            List<Rule> rulearray = ruleMapper.selectByRulenameDeptId(rule);
            // 一个人的规则信息
            for (Rule userrule : rulearray) {
                Integer rule_id = userrule.getId();//规则id
                Integer userid = userrule.getUserid();//用户id
                Integer deptid = userrule.getDeptid();//科室id
                String week = userrule.getWeek();
                //拆分一个week
                String[] weekdetail = week.split("");
                //获得天数 +1
                Integer days = (int) ((over.getTime() - start.getTime()) / (86400000))+1;//使用立即数 减少开销
                //获得开始的星期几 -1
                Calendar cal = Calendar.getInstance();
                cal.setTime(start);
                Integer startweekday = cal.get(Calendar.DAY_OF_WEEK) - 1;
                // 字符串准备
                for (int i = 0; i < weekdetail.length; i++) {
                    if (i%2==0 && "1".equals(weekdetail[i])){
                        weekdetail[i]="上午";
                    }
                    if (i%2==1 && "1".equals(weekdetail[i])){
                        weekdetail[i]="下午";
                    }
                }
                //按天数遍历插入 Scheduling
                for (int i = 0; i < days; i++) {

                    Integer temp = startweekday % 7;//星期几
                    if(temp==0){ temp=7;}//星期日
                    startweekday++;
                    Integer index = (temp-1) * 2;//字符串下标
                    Date sched_date=new Date();
                    Scheduling scheduling = new Scheduling();
                    sched_date.setTime(start.getTime()+i*86400000);//设置日期
                    //上午情况
                    if (!"0".equals(weekdetail[index])){
                        String noon = weekdetail[index];//午别
                        scheduling.setUserid(userid);//设置userid
                        scheduling.setNoon(noon);//设置午别
                        scheduling.setScheddate(sched_date);//设置日期
                        //查询是否有时间冲突
                        Scheduling updateobj = schedulingMapper.selectByIdByScheddateByNoon(scheduling);
                        if (updateobj!=null){
                            //逻辑删除
                            updateobj.setDelmark(0);
                            schedulingMapper.updateByPrimaryKeySelective(updateobj);
                            //覆盖新的排班信息
                            scheduling.setDeptid(deptid);//设置deptid
                            scheduling.setRuleid(rule_id);//设置ruleid
                            schedulingMapper.insert(scheduling);
                        }else{
                            //插入新的排班信息
                            scheduling.setDeptid(deptid);//设置deptid
                            scheduling.setRuleid(rule_id);//设置ruleid
                            schedulingMapper.insert(scheduling);
                        }
                    }
                    //下午情况
                    if (!"0".equals(weekdetail[index+1])){
                        String noon = weekdetail[index+1];//午别
                        scheduling.setUserid(userid);//设置userid
                        scheduling.setNoon(noon);//设置午别
                        scheduling.setScheddate(sched_date);//设置日期
                        //查询是否有时间冲突
                        Scheduling updateobj = schedulingMapper.selectByIdByScheddateByNoon(scheduling);
                        if (updateobj!=null){
                            //逻辑删除
                            updateobj.setDelmark(0);
                            schedulingMapper.updateByPrimaryKeySelective(updateobj);
                            //覆盖新的排班信息
                            scheduling.setDeptid(deptid);//设置deptid
                            scheduling.setRuleid(rule_id);//设置ruleid
                            schedulingMapper.insert(scheduling);
                        }else{
                            //插入新的排班信息
                            scheduling.setDeptid(deptid);//设置deptid
                            scheduling.setRuleid(rule_id);//设置ruleid
                            schedulingMapper.insert(scheduling);
                        }
                    }

                }

            }


        }


        return 1;
        /**
         *  遍历 ruleList
         *
         *    获取rule一个  参数 rulename deptid
         *    获得对应的List<rule>  遍历                                       一个科室 规则名下的 规则集合
         *
         *      拿到一个rule 参数 userid depitid rule_id week                 一个人的规则信息
         *      拆分 week 参数 weekArray[]                                    规则详细
         *      计算天数 days+1 星期几开始startweekday-1
         *      封装一个String[] 14
         *
         *        遍历 weekArray[] 参数ww  i++
         *           if i%2=0  ww=1 String[] add 上午 ww=0  String[] add null
         *           if i%2=1  ww=1 String[] add 下午 ww=0  String[] add null
         *
         *      获得  String[] 14
         *      遍历 days i=0 i++ i< days
         *
         *          startweekday % 7 ==>temp
         *          startweekday++
         *          temp * 2 =>index  String[index]
         *
         *              if(String[index] ！=null) ==> 上午
         *              starttime + i ==> sched_date
         *              获得 userid depitid rule_id sched_date ‘上午’
         *              if （ 查询 scheduling 条件  sched_date ‘上午’  ）
         *               有 {
         *                   逻辑delete  这条信息 update dalmark=0
         *
         *               }
         *               无{
         *                   insert  封装一个scheduling
         *               }
         *
         *
         *              if(String[index+1] ==null) ==> 下午
         *              starttime + i ==> sched_date
         *              获得 userid depitid rule_id sched_date ‘下午’
         *              if （ 查询 scheduling 条件  sched_date ‘下午’  ）
         *               有 {
         *                   逻辑delete  这条信息 update dalmark=0
         *
         *               }
         *               无{
         *                   insert  封装一个scheduling
         *               }
         *
         *         i > days  结束
         *
         *       List<rule> 结束
         *
         *     ruleList 结束
         *
         *
         */
















    }

    @Override
    public Scheduling selectByPrimaryKey(Integer id) {
        return null;
    }

    @Override
    public List<Scheduling> selectByCondition(String starttime, String overtime, Integer deptid) {

        Map<String, Object> map = new HashMap<>();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date start = new Date();
        Date over = new Date();
        try {
            start=df.parse(starttime);
            over=df.parse(overtime);
            map.put("starttime",start);
            map.put("overtime",over);
            map.put("deptid",deptid);
            return schedulingMapper.selectByCondition(map);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int updateByPrimaryKeySelective(Scheduling record) {
        return 0;
    }

    @Override
    public int updateByPrimaryKey(Scheduling record) {
        return 0;
    }
}
